package data;

import java.util.Timer;
import java.util.TimerTask;

import connection.Relay;
import connection.SensorMessage;

public class InputFileRecordHandler implements Runnable {
	private InputFileRelay fileRelay;
	private Timer timer;
	private Relay connRelay;
	private int lastInterval = 0;
	
	public InputFileRecordHandler(InputFileRelay fileRelay, Relay connRelay) {
		this.fileRelay = fileRelay;
		this.connRelay = connRelay;
	}
	
	@Override
	public void run() {
		timer = new Timer();
		
		while(true) {
			InputFileRecord record = fileRelay.getRecord();
			if (record != null) {
				lastInterval = record.getInterval();
				MessageTask task = new MessageTask(connRelay, record);
				timer.schedule(task, record.getInterval() - lastInterval);
			}
			
			try {
				Thread.sleep(100);
			} 
			catch (InterruptedException e) {
				e.printStackTrace();
			}
		}		
	}
}

class MessageTask extends TimerTask {
	private Relay connRelay;
	private InputFileRecord record;
	
	public MessageTask(Relay connRelay, InputFileRecord record) {
		super();
		this.connRelay = connRelay;
		this.record = record;
	}
	
	@Override
	public void run() {
		connRelay.addSensorMessage(new SensorMessage(record.getLane(), 1));
	}
}
